package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.ProductVo;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 设备信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotDAClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     *
     * @param deviceDto 设备信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice(DeviceDto deviceDto) {
//        return updateById(device) ? 1 : 0;
        //- 注意：修改之后，不能在同一个位置绑定同一个产品
        //判断是否在同一个位置绑定了同一个产品，如果是，就不能修改
        isProduct(deviceDto);

        //- 先修改IoTDA平台上的设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(deviceDto.getIotId());

        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        request.setBody(body);

        UpdateDeviceResponse response = iotDAClient.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {

            throw new BaseException("远端修改设备名称失败");
        }


        //- 再修改本地存储的设备信息
        Device device = BeanUtil.toBean(deviceDto, Device.class);

        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        this.update(device, Wrappers.<Device>lambdaUpdate().eq(Device::getId, device.getId()));


    }

    /**
     * 判断不能在同一个位置绑定同一个产品
     *
     * @param deviceDto
     */
    private void isProduct(DeviceDto deviceDto) {
        //1.1找到这个id的数据，然后把前端传过来的productName 产品信息对比，
        // 1.2如果是同一个产品，然后比较是不是同一个位置（locationType是否相等，如果都是0怎么样，如果是都1,怎么样。然后比较绑定的具体人或楼层是否相等），然后就是，如果是，就不能绑定，也不修改
        Device device = this.getById(deviceDto.getId());
        //查看产品是否相等，这里其实不用，因为前端已经锁死不让修改
        if (device.getProductName().equals(deviceDto.getProductName())) {
            //判断位置类型是否修改了
            if (device.getLocationType().equals(deviceDto.getLocationType())) {
                long count = 0;
                //判断接入位置是否相等
                if (StringUtils.isEmpty(deviceDto.getDeviceDescription())) {
                    count = this.count(Wrappers.<Device>lambdaQuery()
                                    .eq(Device::getBindingLocation, String.valueOf(deviceDto.getBindingLocation()))
//                        .eq(Device::getDeviceDescription, deviceDto.getDeviceDescription())
                                    //排除当前节点，
                                    .ne(Device::getId, deviceDto.getId())
                    );
                } else {
                    count = this.count(Wrappers.<Device>lambdaQuery()
                            .eq(Device::getBindingLocation, String.valueOf(deviceDto.getBindingLocation()))
                            .eq(Device::getDeviceDescription, deviceDto.getDeviceDescription())
                            //排除当前节点，
                            .ne(Device::getId, deviceDto.getId())
                    );
                }
                if (count > 0) {
                    //说明重复了，就返回不能修改
                    throw new BaseException("不能在同一个位置绑定同一个产品");
                }
            } else {
                throw new BaseException("不能在同一个位置绑定同一个产品");
            }
        } else {
            throw new BaseException("不能在同一个位置绑定同一个产品");
        }
    }


    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     *
     * @param iotId 设备信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeviceByIotId(String iotId) {
        //删除本地设备，再删除远端设备
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);

        DeleteDeviceResponse response = iotDAClient.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("远端删除失败");
        }

    }

    /**
     * 从物联网平台同步产品列表  Ctrl + i  快速产生下面的方法
     */
    @Override
    public void syncProductList() {
        //设置请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //  设置条数
        listProductsRequest.setLimit(50);
        //向Iot平台发起请求
        ListProductsResponse listProductsResponse = iotDAClient.listProducts(listProductsRequest);
        if (listProductsResponse.getHttpStatusCode() != 200) {
            throw new BaseException("请求Iot平台失败");
        }
        //存储到Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String s = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST).toString();
        if (StringUtils.isEmpty(s)) {
            //返回一个空列表
            return Collections.emptyList();
        }
        List<ProductVo> list = JSONUtil.toList(s, ProductVo.class);


        return list;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {

        //设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            //说明重复了
            throw new BaseException("设备名称重复");
        }
        //设备标识是否重复
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, deviceDto.getNodeId())

        );
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }

        //同一位置是否绑定了相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())//物理位置类型,需要判断物理位置是否存在
        );
        if (count > 0) {
            throw new RuntimeException("设备已存在");
        }

        //注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());
        addDevice.setDeviceName(deviceDto.getDeviceName());


        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);

        addDevice.setAuthInfo(authInfo);
        addDeviceRequest.setBody(addDevice);

        AddDeviceResponse addDeviceResponse = iotDAClient.addDevice(addDeviceRequest);
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new RuntimeException("添加设备失败");
        }

        String deviceId = addDeviceResponse.getDeviceId();


        //本地保存设备
        //拷贝属性
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(deviceId);
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));

        device.setSecret(secret);

        this.save(device);

    }

    /**
     * 查询设备详细数据
     *
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {

        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }


        //连接客户端，获取更多的设备信息

        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(String.valueOf(iotId));
        ShowDeviceResponse response = iotDAClient.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();

        //封装数据

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(status);
        //如果未启动状态，时间是空，所以需要判断
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = DateTimeZoneConverter.utcToShanghai(activeTime);
            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {

        //查询在线数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
//            return Collections.emptyList();//获取失败
            throw new BaseException("查询设备影子数据失败");
        }

        //取出数据
        List<DeviceShadowData> shadow = response.getShadow();
        //如果这个数据是空
        if (CollectionUtils.isEmpty(shadow)) {
            return Collections.emptyList();
        }
        //获取设备影子数据
        DeviceShadowProperties reported = shadow.get(0).getReported();

        Object properties = reported.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties);

        String eventTime = reported.getEventTime();
        //转换时间
        LocalDateTime time = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        //时区转换
        LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(time);

        List<Map<String, Object>> list = new ArrayList<>();

        jsonObject.forEach((key, value) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", localDateTime);
            list.add(map);
        });
        return list;
    }


    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {

        if (StringUtils.isEmpty(productKey)) {
            //说明没有传过来,返回一个空集合
            return Collections.emptyList();
        }

        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);


        ShowProductResponse response = iotDAClient.showProduct(request);

        if (response.getHttpStatusCode()!=200){
            throw  new BaseException("查询产品失败");
        }
        //获取service_capabilities
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();

        if (CollectionUtils.isEmpty(serviceCapabilities)){
            throw new BaseException("产品没有服务");
        }
        return serviceCapabilities;
    }


}
